<?php
/**
 * 会员动态
 * @return
 * @author yuncran@126.com
 */

namespace app\model;

use app\BaseModel;
use app\CacheKey;
use app\FieldKey;
use think\facade\Db;

class TrendsModel extends BaseModel
{

    protected $name = 'trends';

    protected $pk = "id";
    protected $jsonAssoc = true;

    protected $append = ['user'];

    public function getUserAttr($value, $data)
    {
        return UserModel::where(['id' => $data['user_id']])->field(FieldKey::user_field_has_one)->append(['level_result'])
            ->withAttr('level_result', function ($value, $data) {
                return UserLevelModel::where(['id' => $data['level']])
                    ->field(['id', field('title'), 'describe', 'image', 'money', 'expire', 'color', 'font_color', 'background_image', 'create_time'])
                    ->cache(CacheKey::level_title)->find();
            })->find();
    }


    /**
     * 增加数据
     * @param $trends_id
     * @param $field
     * @param $size
     * @return mixed
     * @author yuncran@126.com
     */
    public static function addTrendsInc($use_id, $trends_id, $field, $size = 1)
    {
        if ($field == 'collect_number') {
            UserCensusCountModel::where('user_id', $use_id)->inc('user_collect_count', $size)->update();
        }
        if ($field == 'share_number') {
            UserCensusCountModel::where('user_id', $use_id)->inc('user_trends_count', $size)->update();
        }
        return self::getModel()->where('id', $trends_id)->inc($field, $size)->update();
    }

    /**减少数据
     * @param $trends_id
     * @param $field
     * @param $size
     * @return mixed
     * @author yuncran@126.com
     */
    public static function minusTrendsDec($use_id, $trends_id, $field, $size = 1)
    {
        if ($field == 'collect_number') {
            UserCensusCountModel::where('user_id', $use_id)->dec('user_collect_count', $size)->update();
        }
        if ($field == 'share_number') {
            UserCensusCountModel::where('user_id', $use_id)->dec('user_trends_count', $size)->update();
        }
        return self::getModel()->where('id', $trends_id)->dec($field, $size)->update();
    }


    /** 获取动态 */
    public static function getTrends($trends_id)
    {
        $res = self::getModel()->where('id', $trends_id)->field('id,content,user_id,image,video')->find();
        $res['content'] = empty($res['content']) ? lang('视频或图片') : $res['content'];
        return $res;
    }
}